<template>
  <el-form label-width="80px" ref="userFormRef" :model="userForm" :rules="userFormRules">
    <el-form-item label="原密码:" prop="password">
      <el-input v-model.trim="userForm.password" type="password" placeholder="请输入原密码" clearable />
    </el-form-item>
    <el-form-item label="新密码:" prop="newpassword">
      <el-input v-model="userForm.newpassword" type="password" placeholder="请输入新密码" clearable />
    </el-form-item>
    <el-form-item label="密码确认:" prop="repassword">
      <el-input
        v-model.trim="userForm.repassword"
        type="password"
        placeholder="请重新输入新密码"
        clearable
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updatePassword } from "@/api/user";
export default {
  props: {
    username: ""
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 6 || value.lenght > 15) {
        callback(new Error("密码长度在6~15个字符之间"));
      } else {
        if (this.userForm.repassword !== "") {
          this.$refs.userFormRef.validateField("repassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入新密码"));
      } else if (value !== this.userForm.newpassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      userForm: {
        username: "",
        password: "",
        newpassword: "",
        repassword: ""
      },
      userFormRules: {
        password: [
          { required: true, message: "请输入原密码", trigger: "blur" }
        ],
        newpassword: [{ validator: validatePass, trigger: "blur" }],
        repassword: [{ validator: validatePass2, trigger: "blur" }]
      }
    };
  },
  methods: {
    submit() {
      this.userForm["username"] = this.username     
      this.$refs.userFormRef.validate( (valid) => {
        if(valid){
          updatePassword(this.userForm).then( res => {
            console.log(res);
            if(res.status_code === 200){
              this.$refs["userFormRef"].resetFields();
              this.$message({
                message: res.message,
                type: "success",
                duration: 5 * 1000
              });
            } else {
              this.$message.error("密码修改失败。")
            }
          }).catch( error => {
            console.log(error);
          })
        } else {
          return false
        }
      } );
     
      
    }
  }
};
</script>

<style lang='scss' scoped>
.el-input,
.el-select {
  width: 50%;
}
</style>